package widget.common.managers
{
	import flash.errors.IOError;
	import flash.events.*;
	import flash.net.*;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	
	import widget.common.utils.MyLog;
	import widget.common.event.ConnectionEvent;
	
	[Event(name="connect_complete", type="widget.common.event.ConnectionEvent")]
	[Event(name="connect_error", type="widget.common.event.ConnectionEvent")]
	[Event(name="connect_progress", type="widget.common.event.ConnectionEvent")]
	public class ConnectionManager extends EventDispatcher {
		public function ConnectionManager() {
			super(null);
		}
		
		public function loadMessage(para:URLVariables,url:String,type:String = "post",format:String = "variables"):void{
			var request:URLRequest=new URLRequest; 
			request.data=para;
			request.url=url;
			request.method = type;
			
			//发送数据     
			var loader:URLLoader=new URLLoader;
			loader.dataFormat = format;
			
			loader.addEventListener(Event.COMPLETE,completeHandler);
			loader.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
			loader.addEventListener(ProgressEvent.PROGRESS,progressHandler);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,securityHandler);
			try {
				//MyLog.debug("ddddd"+url);
				loader.load(request);
			} catch (e:Error) {
				throw new Error(e.message);
			}
		}
		
		public function clear():void{
			
		}
		
		private function completeHandler(e:Event):void {
			//处理返回的结果，如果插入数据库成功那么就可以  
			var evt:ConnectionEvent=new ConnectionEvent(ConnectionEvent.CONNECT_COMPLETE,URLLoader(e.target));
			this.dispatchEvent(evt);
		}
		
		private function ioErrorHandler(event:IOErrorEvent):void {
			this.dispatchEvent(new ConnectionEvent(ConnectionEvent.CONNECT_ERROR,null,event.text));
			//MyLog.debug("load io error!!!!!");
		}
		
		private function progressHandler(event:ProgressEvent):void{
			this.dispatchEvent(new ConnectionEvent(ConnectionEvent.CONNECT_PROGRESS,null));
		}
		
		private function securityHandler(event:SecurityErrorEvent):void{
			//MyLog.debug("load security error!!!!!");
		}
	}
}